package com.hippo.core.vm

import android.content.Context
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hippo.core.BaseApplication
import com.hippo.core.core.UserManger
import com.hippo.core.core.ext.toMd5
import com.hippo.core.dto.RegisterDto
import com.hippo.core.respository.ApiRepository
import com.hippo.core.state.RegisterState
import com.hippo.core.tuya.TuYaManager
import com.hippo.core.utils.AppUtil
import com.hippo.core.utils.UiHandler
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class RegisterVM : ViewModel() {

    var uiState by mutableStateOf(RegisterState())


    init {

        getCountryList{
            val country = uiState.countryList?.firstOrNull()
            country?.let {
                uiState = uiState.copy(
                    countryId  = country.countryId,
                    countryCode  = country.countryCode,
                    englishName  = country.englishName,)
            }
        }

    }


    fun dismissLoading(){
        uiState = uiState.copy(isLoading = false)
    }


    fun updateState(state: RegisterState) {
        uiState = state
    }

    
    
    fun register(context: Context) {

        if(uiState.userEmail.isNullOrBlank()){
            updateState(uiState.copy(userEmailError = true))
            return
        }
        if(uiState.verifyCode.isNullOrBlank()){
            updateState(uiState.copy(userEmailError = false,verifyCodeError = true))
            return
        }
        if(uiState.password.isNullOrBlank()){
            updateState(uiState.copy(userEmailError = false,verifyCodeError = false,passwordError = true))
            return
        }

        if(uiState.confirmPassword.isNullOrBlank()){
            updateState(uiState.copy(userEmailError = false,verifyCodeError = false,passwordError = false,confirmPasswordError = true))
            return
        }

        viewModelScope.launch {
            uiState = uiState.copy(isLoading = true)

            val dto = RegisterDto(
                confirmPassword = uiState.confirmPassword?.toMd5(),
                countryId = uiState.countryId,
                password = uiState.password?.toMd5(),
                userEmail = uiState.userEmail,
                verifyCode = uiState.verifyCode
            )
            ApiRepository.userRegister(dto)
                .onFailure {
                    UiHandler.showToast(it.msg)
                }
                .onSuccess { userInfo->
//                    UiHandler.showToast("注册成功")
//                    UserManger.saveUserInfo(it)
//                    uiState = uiState.copy(isLoading = false, registerSuccess = true)

                    val uid = AppUtil.getAndroidId(context)

                    Log.d("register", "register: uid: $uid")

                    TuYaManager.loginOrRegisterWithUid(
                        countryCode = uiState.countryCode!!,
                        uid = uid,
                        passwd = uiState.password?.toMd5().orEmpty(),
                        onSuccessCallback = {
                            UserManger.saveUserInfo(userInfo)
                            uiState = uiState.copy(isLoading = false, registerSuccess = true)
                        },
                        onErrorCallback = { code, msg ->
                            uiState = uiState.copy(isLoading = false, registerSuccess = false)
                            UiHandler.showToast(msg)
                        }
                    )
                }

        }

    }

    fun sendEmailCode(){

        if(uiState.userEmail.isNullOrBlank()){
            uiState = uiState.copy(userEmailError = true)
            return
        }

        uiState = uiState.copy(isLoading = true)

        viewModelScope.launch {
            ApiRepository.sendEmailCode(uiState.userEmail!!,"1")
                .onFailure {
                    uiState = uiState.copy(isLoading = false)
                    UiHandler.showToast(it.msg)
                }
                .onSuccess {
                    uiState = uiState.copy(isLoading = false)
                    startCountDown()
                }
        }


    }


    fun startCountDown(){
        var count = 60
        viewModelScope.launch{
            while (count > 0) {
                delay(1000)
                count--
                uiState = uiState.copy(countDown = count)
            }
        }
    }


    fun getCountryList(callback:()->Unit) {
        if(uiState.countryList == null){
            viewModelScope.launch {
                ApiRepository.getCountryList()
                    .onSuccess {
                        uiState = uiState.copy(countryList = it)
                        callback()
                    }
            }
        }else{
            callback()
        }


    }


}